package com.bot.rf.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import static com.bot.rf.util.MyLogger.LOGGER;
public class HttpUtil {

    /**
     * 通过httpClient上传文件
     * @param fileName
     */
    public static boolean UploadFileByHttpClient(String fileName) {
        LOGGER.info("报表上传后台...");
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse httpResponse = null;
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
        try {
            HttpPost httpPost = new HttpPost("http://124.70.8.106:8889/rest/form/upload");
            httpPost.setConfig(requestConfig);
            //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            File file = new File(fileName);
            builder.addBinaryBody("file", file);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200){
                LOGGER.info("报表上传后台成功");
                return true;
            }
        }catch(Exception e) {
            LOGGER.error("上传文件失败：",e);
        }finally {//处理结束后关闭httpclient的链接
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}
